<?php
namespace app\spadmin\command;

use think\console\Command;
use think\console\Input;
use think\console\input\Option;
use think\console\Output;
use think\Exception;
use app\common\model\User;
use app\common\model\WechatUser;
use EasyWeChat\Factory;
use think\Log;
use think\Db;

class Attention extends Command
{
     protected function configure()
    {
        $this->setName('attention')->setDescription('attention user ');
    }

    protected function execute(Input $input, Output $output)
    {

        $this->attention();
    }
    
    /***
     * 关注用户
     */
    protected function attention(){
        $config = [
            'app_id' => 'wxa18b9c41a69c61da',
            'secret' => '7d15d5ec278c6fc30e6e3a34a307b261',
            'response_type' => 'array',
        ];
        $app = Factory::officialAccount($config);
        $nextOpenId = null;
        $wechatUser=[];
        $count = 1;
        while ($count > 0) {
            $list = $app->user->list($nextOpenId);
            $count = $list['count'];
            if($count>0){
                $wechatUser = array_merge($wechatUser,$list['data']['openid']);
            }
            $nextOpenId = $list['next_openid'];
            
        }
        foreach ($wechatUser as $key => $value) {
           $openid = $app->user->get($value);
           if(isset($openid['unionid']) && $openid['unionid']){
            $this->checkAttention($openid);
           }
        }
        
    }
    /***
     * 关注验证用户并得积分
     */
    protected function checkAttention($openid){
        $user = User::get(['unionid'=>$openid['unionid']]);
        if(!empty($user)){
            Db::startTrans();
            try {
                if($user['is_attention'] != 1){
                    //关注获得积分逻辑
                    /**********
                     * 
                     * 
                    */
                }
                $user->is_attention = 1;
                $user->wechat_openid = $openid['openid'];
                $user->save();
                Db::commit();
            } catch (\think\exception $e) {
                Db::rollback();
            }
        }
            
    }
}